﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Data.SqlTypes;
using System.Data.SqlClient;
using System.Data;
using System.Configuration;
using System.Net.NetworkInformation;
using System.Net;
using System.Security.Principal;
using System.Windows.Forms;
using DevExpress.XtraEditors.Repository;
using System.Collections;
using COMOSOFT.OrderBusiness.Forms;
using COMOSOFT.JobManagement.Froms;
using System.IO;
using DevExpress.XtraGrid.Views.Grid;
using DevExpress.XtraEditors;

namespace COMOSOFT.Class
{    
   public class ClassShare
    {
       public static Main.FrmMain frmain = null;
       public static FrmJobView frjobview = null;
       public static MatarialManagement.Forms.FrmMALibrary frMALib = null;
       public static MatarialManagement.Forms.FrmMaterial frMA = null;
       public static MatarialManagement.Forms.FrmMAGeneralView frFabricGV = null;
       public static MatarialManagement.Forms.FrmAccessoriesView frAcessV = null;
       public static int Usid,fpid;
       public static string Usname, UserN, Pass,Email,Position,StaffNo;
       static String ip = null;
       static String macAdd = null;      
       public static bool IsRemember = false;
       public static string Image = null;
       public static string connect = @"Data Source=comosoft.ddns.net,1324;Initial Catalog=COMO;User ID=como;Password=@Admin324";

       public static string host = "ftp://comosoft.ddns.net/Documents/";
       string Userftp = "comosoft";
       string Passftp = "@como123";      

       //host ftp
       public static String ftpJobAssign = System.Configuration.ConfigurationManager.AppSettings["JobAssign"].ToString();
       public static String ftpMaterial = System.Configuration.ConfigurationManager.AppSettings["Material"].ToString();
       public static String ftpSystem = System.Configuration.ConfigurationManager.AppSettings["System"].ToString();      
       public static String ftpOrder= System.Configuration.ConfigurationManager.AppSettings["Order"].ToString();
       public static String ftpWareHouse = System.Configuration.ConfigurationManager.AppSettings["WareHouse"].ToString();
       //local
       public static String lcJobAsign = @"C:\COMOSOFT_APP\JobAssign\FileAttach\";
       public static String lcMaterial = @"C:\COMOSOFT_APP\Material\Image\";
       public static String lcSystem = @"C:\COMOSOFT_APP\System\Image\";
       public static String lcOrder = @"C:\COMOSOFT_APP\Order\Image\";
       public static String lcWareHouse = @"C:\COMOSOFT_APP\WareHouse\File\";
       String formname;
       //
        
       //var report
       public static string FPMIDs,OIDs;       
       //
       public ClassShare(string formname)
       {
           this.formname = formname;
       }
       //---------------------------
       //
       #region[Login]
       public SqlConnection connection()
       {
           SqlConnection con = new SqlConnection(connect);
            if (con.State == ConnectionState.Closed)
            {
                con.Open();
            }
            return con;
       }
       //Dowloadfile
       public void Dowload(string host,string path,string localfile)
       {
           WebClient WC = new WebClient();
           WC.Credentials = new NetworkCredential(Userftp, Passftp);
           byte[] fileData = WC.DownloadData(host +@"/"+ localfile);
           Stream fileStream = File.Create(path + localfile);
           fileStream.Write(fileData, 0, fileData.Length);
           fileStream.Close();
       }
      //Upload File
       public void UploadFile(string filename, string host)
       {
           //WebClient WC = new WebClient();
           //WC.Credentials = new System.Net.NetworkCredential(Userftp, Passftp);
           //WC.UploadProgressChanged += UploadProgessChanged;
           //WC.UploadDataCompleted += UploadCompleted;
           //WC.UploadDataAsync(new Uri(host), filename);
        ////   internal void upload(string type, string preFix, string localfile)
        ////{
           FileInfo upFile = new FileInfo(filename);
           FtpWebRequest request = (FtpWebRequest)WebRequest.Create(String.Format("{0}/{1}", host, upFile.Name));
           request.Method = WebRequestMethods.Ftp.UploadFile;
           request.Credentials = new NetworkCredential(Userftp, Passftp);
           Stream ftpStream = request.GetRequestStream();
           FileStream file = File.OpenRead(filename);
           int lenght = 1024;
           byte[] buffer = new byte[lenght];
           int byteRead = 0;
           do
           {
               byteRead = file.Read(buffer, 0, lenght);
               ftpStream.Write(buffer, 0, byteRead);
           }
           while (byteRead != 0);
           file.Close();
           ftpStream.Close();
       // }
       }
       private void UploadProgessChanged(object sender, System.Net.UploadProgressChangedEventArgs e)
       {
           //if (e.ProgressPercentage >= 0 && progressBar.Visible == false)
           //{
           //    ShowProgessPannel(progressBar, this);
           //}
           //progressBar.EditValue = e.ProgressPercentage;
       }
       private void UploadCompleted(object sender, System.Net.UploadDataCompletedEventArgs e)
       {
           if (e.Cancelled == true)
           {
               MessageBox.Show("Cancelled");
           }
           else if (e.Error != null)
           {
               MessageBox.Show(e.Error.Message);
           }
           //hideP(progressBar);
           //OpenFolder(_currentFolder, false);
       }
      //-----------------------
       //Create Folder
       public void CreateFolder()
       {
           try
           {
               if (!System.IO.Directory.Exists(@"C:\COMOSOFT_APP"))
               {
                   System.Security.AccessControl.DirectorySecurity permission = new System.Security.AccessControl.DirectorySecurity();                  
                   System.IO.Directory.CreateDirectory(@"C:\COMOSOFT_APP\JobAssign\FileAttach");
                   System.IO.Directory.CreateDirectory(@"C:\COMOSOFT_APP\System\Image");
                   System.IO.Directory.CreateDirectory(@"C:\COMOSOFT_APP\Material\Image");                   
                   System.IO.Directory.CreateDirectory(@"C:\COMOSOFT_APP\Order\Image");                   
               }
           }
           catch
           { 
           }
       }
       //Save Layout
       public void SaveLayout(GridView view,string path)
       {
           if (File.Exists(path))
               File.Delete(path);
           FileStream str = new FileStream(path, FileMode.Create);
           str.Close();
           view.SaveLayoutToXml(path);
           MessageBox.Show("Save layout successfully!");
       }
       public void LoadLayout(GridView view, string path)
       {
           if (File.Exists(path))
           {
               view.RestoreLayoutFromXml(path);
           }
       }
       //
       #region [AutoComplete]

       public void AutoComplete(TextBox txt,DataTable dtb)
       {
           AutoCompleteStringCollection autocl = new AutoCompleteStringCollection();
           txt.AutoCompleteMode = AutoCompleteMode.Append;
           txt.AutoCompleteSource = AutoCompleteSource.CustomSource;
           txt.AutoCompleteMode = AutoCompleteMode.Suggest;
           txt.AutoCompleteSource = AutoCompleteSource.CustomSource;

           if (dtb != null)
           {
               for (int i = 0; i < dtb.Rows.Count; i++)
               {
                   autocl.Add(dtb.Rows[i][0].ToString());
               }
           }
           txt.AutoCompleteMode = AutoCompleteMode.Suggest;
           txt.AutoCompleteSource = AutoCompleteSource.CustomSource;
           txt.AutoCompleteCustomSource = autocl;
       }
       #endregion

       internal bool checklogin(String user, string pass)
        {
            SqlCommand cmd = new SqlCommand("select * from Employee where account=@user and password=@pass", this.connection());
            cmd.Parameters.Add("@user", SqlDbType.VarChar);
            cmd.Parameters["@user"].Value = user;
            cmd.Parameters.Add("@pass", SqlDbType.VarChar);
            cmd.Parameters["@pass"].Value = pass;
            SqlDataReader dr = cmd.ExecuteReader();
            if (dr.Read())
            {
                UserN = user;
                Pass = pass;
                Usid = int.Parse(dr.GetSqlValue(0).ToString());
                StaffNo = dr.GetSqlValue(1).ToString();
                Usname = dr.GetSqlValue(4).ToString();
                Email = dr.GetSqlValue(9).ToString();
                Position = dr.GetSqlValue(13).ToString();
                Image = dr.GetSqlValue(14).ToString();
                this.connection().Close();
                //createDirectory(directoryPath + UserN);
                //path = directoryPath + UserN + "/" + UserN + "_Mlog.txt";
                ip = GetIP();
                macAdd = getMacAddress();
                return true;
            }
            else
            {
                UserN = null;
                Pass = null;
                Usid = 0;
                MessageBox.Show("Please check agian,Cannot access systems!", "Login Fail!", MessageBoxButtons.OK, MessageBoxIcon.Warning);          
                this.connection().Close();
                return false;
            }
        }
       public string GetIP()
       {
           string strHostName = "";
           strHostName = Dns.GetHostName();
           IPHostEntry ipEntry = Dns.GetHostEntry(strHostName);
           IPAddress[] addr = ipEntry.AddressList;
           string cpname = WindowsIdentity.GetCurrent().Name.ToString();
           return " CompName:" + cpname + "***IP:" + addr[addr.Length - 1].ToString();
       }
       public string getMacAddress()
       {
           String macAddress = null;
           IPGlobalProperties computerProperties = IPGlobalProperties.GetIPGlobalProperties();
           NetworkInterface[] nics = NetworkInterface.GetAllNetworkInterfaces();
           if (nics == null || nics.Length < 1)
           {
               return "";
           }
           NetworkInterface adapter = nics[0];
           PhysicalAddress address = adapter.GetPhysicalAddress();
           macAddress = "-MacAddress:" + address.ToString();
           return macAddress;
       }

       public DataTable CheckEmployee(int id)
       {
           SqlCommand command = new SqlCommand("sp_CheckEmployee", this.connection());
           command.CommandType = CommandType.StoredProcedure;
           command.Parameters.AddWithValue("@EID",id);
           command.ExecuteNonQuery();
           SqlDataAdapter adt = new SqlDataAdapter(command);
           DataTable dtb = new DataTable();
           adt.Fill(dtb);
           return dtb;
       }

       public DataTable GetData(string sql)
       {
           SqlCommand command = new SqlCommand(sql, this.connection());
           command.CommandType = CommandType.StoredProcedure;
           SqlDataAdapter adt = new SqlDataAdapter(command);
           DataTable dtb = new DataTable();
           adt.Fill(dtb);
           this.connection().Close();
           return dtb;
       }
       //update data
       public DataTable GetData(string sql, string[] name, object[] value)
       {
           SqlCommand command = new SqlCommand(sql, this.connection());
           command.CommandType = CommandType.StoredProcedure;
           for (int i = 0; i < name.Length; i++)
           {
               command.Parameters.AddWithValue(name[i], value[i]);
           }
           SqlDataAdapter adt = new SqlDataAdapter(command);
           DataTable dtb = new DataTable();
           adt.Fill(dtb);
           this.connection().Close();
           return dtb;
       }
       
       public int UpdateData(string sql)
       {
           SqlCommand command = new SqlCommand(sql, this.connection());
           command.CommandType = CommandType.StoredProcedure;
           int kq = command.ExecuteNonQuery();
           this.connection().Close();
           return kq;
       }
       public int UpdateData(string sql, string[] name, object[] value)
       {
           SqlCommand command = new SqlCommand(sql, this.connection());
           command.CommandType = CommandType.StoredProcedure;
           for (int i = 0; i < name.Length; i++)
           {
               command.Parameters.AddWithValue(name[i], value[i]);
           }
           int kq = command.ExecuteNonQuery();
           this.connection().Close();
           return kq;
       }
       //--------------------------------
    #endregion

       #region [DatasetToArrayList]
       internal ArrayList DataSetToArrayList(int ColumnIndex, DataTable dataTable)
       {
           ArrayList list = new ArrayList();
           foreach (DataRow row in dataTable.Rows)
           {
               list.Add(row[ColumnIndex]);
           }
           return list;
       }
       #endregion

       #region [SelectDistionct]
       internal DataTable SelectDistinct(DataTable SourceTable, params string[] FieldNames)
       {
           object[] lastValues;
           DataTable newTable;
           DataRow[] orderedRows;

           if (FieldNames == null || FieldNames.Length == 0)
               throw new ArgumentNullException("FieldNames");

           lastValues = new object[FieldNames.Length];
           newTable = new DataTable();

           foreach (string fieldName in FieldNames)
               newTable.Columns.Add(fieldName, SourceTable.Columns[fieldName].DataType);

           orderedRows = SourceTable.Select("", string.Join(", ", FieldNames));

           foreach (DataRow row in orderedRows)
           {
               if (!fieldValuesAreEqual(lastValues, row, FieldNames))
               {
                   newTable.Rows.Add(createRowClone(row, newTable.NewRow(), FieldNames));

                   setLastValues(lastValues, row, FieldNames);
               }
           }

           return newTable;
       }
       private static bool fieldValuesAreEqual(object[] lastValues, DataRow currentRow, string[] fieldNames)
       {
           bool areEqual = true;

           for (int i = 0; i < fieldNames.Length; i++)
           {
               if (lastValues[i] == null || !lastValues[i].Equals(currentRow[fieldNames[i]]))
               {
                   areEqual = false;
                   break;
               }
           }

           return areEqual;
       }
       private static DataRow createRowClone(DataRow sourceRow, DataRow newRow, string[] fieldNames)
       {
           foreach (string field in fieldNames)
               newRow[field] = sourceRow[field];

           return newRow;
       }

       private static void setLastValues(object[] lastValues, DataRow sourceRow, string[] fieldNames)
       {
           for (int i = 0; i < fieldNames.Length; i++)
               lastValues[i] = sourceRow[fieldNames[i]];
       }
       #endregion

       #region [AddingList]
       internal void AddingListRepCombo(RepositoryItemComboBox[] Ctl, DataTable tb, string[] ColName)
        {
            for (int i = 0; i < ColName.Length; i++)
            {
                ArrayList Drow = null;
                Drow = DataSetToArrayList(0, (SelectDistinct(tb, ColName[i])));
                Ctl[i].Items.Clear();
                Ctl[i].Items.AddRange(Drow);
            }
        }

        #endregion
    
    }  
}
